﻿using System;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WinRTControl;
using System.Linq;

namespace KouDai.WinPad.Helper
{
    public class BusyInicator
    {
        #region Sigleton

        private ProgressBar _progressIndicator;

        private static BusyInicator _instance;

        private BusyInicator()
        {
          
        }

        public static BusyInicator Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new BusyInicator();
                }
                return _instance;
            }
        }

        #endregion

        public void Init(Frame rootFrame)
        {
            rootFrame.Navigating += rootFrame_Navigating;
            rootFrame.Navigated += rootFrame_Navigated;
        }


        void rootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            if (IsBusy)
            {
                IsBusy = false;
            }
        }


        void rootFrame_Navigated(object sender, NavigationEventArgs e)
        {
            Page page = e.Content as Page;
            if (page != null)
            {
                _progressIndicator = new ProgressBar();
                _progressIndicator.IsIndeterminate = false;
                _progressIndicator.Visibility = Visibility.Collapsed;

                //set to page
                _progressIndicator.SetValue(Grid.VerticalAlignmentProperty, VerticalAlignment.Top);
                _progressIndicator.Margin = new Windows.UI.Xaml.Thickness(0, 10, 0, 0);
                var frameworkElement = page.Descendents().ToList().First();
                if (frameworkElement is Grid)
                {
                    Grid firstGrid = (Grid)frameworkElement;
                    firstGrid.Children.Add(_progressIndicator);
                }
                else
                {
                    throw new InvalidOperationException("Page is error !");
                }
            }
        }

        private bool _isBusy;

        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                if (_progressIndicator != null)
                {
                    _progressIndicator.Visibility = value ? Visibility.Visible : Visibility.Collapsed;
                    _progressIndicator.IsIndeterminate = value;
                }
            }
        }
    }
}
